package com.bdc.action;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bdc.bean.Product;
import com.bdc.service.ProductService;
import com.bdc.service.ServiceFactory;

public class PagedProductListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final int PAGED_COUNT = 24;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String productType = req.getParameter("productType");
		String pageIndex = req.getParameter("pageIndex");
		int index = 0;
		if(pageIndex != null) {
			index = Integer.parseInt(pageIndex);
		}
		ProductService productService = ServiceFactory.getProductService();
		List<Product> products = productService.getPagedList(productType,index * PAGED_COUNT, index * PAGED_COUNT + PAGED_COUNT);
		
		boolean hasNextPages = false; 
		int nextPageIndex = 0;
		if(index != 0 || products.size() == 24) {
			nextPageIndex = index +  1;
		}
		
		hasNextPages = productService.hasNextPages(productType, index * PAGED_COUNT + PAGED_COUNT);
		
		req.setAttribute("nextPageIndex", String.valueOf(nextPageIndex));
		req.setAttribute("productType", productType);
		req.setAttribute("hasNextPages", Boolean.valueOf(hasNextPages));
		req.setAttribute("products", products);
		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/jsp/product/paged_products.jsp");
		dispatcher.forward(req, resp);
	}
}
